<template>
	<a-drawer
		:title="formData.id ? '编辑物品' : '增加物品'"
		:width="1200"
		:visible="visible"
		:destroy-on-close="true"
		:footer-style="{ textAlign: 'right' }"
		@close="onClose"
		:mask-closable="false"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-tabs v-model:activeKey="activeKey">
				<a-tab-pane key="base" tab="基本信息">
					<a-row :gutter="24">
						<a-col :span="12">
							<a-form-item label="物品编号：" name="goodsCode">
								<a-input v-model:value.trim="formData.goodsCode" placeholder="请输入编号" allow-clear
										 :disabled="formData.id && formData.unknownFlag !=1"/>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="物品名称：" name="goodsName">
								<a-input v-model:value.trim="formData.goodsName" placeholder="请输入名称" allow-clear/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="识别方式：">
								<a-row>
									<a-col :span="8">RFID：
										<a-switch v-model:checked="rfidFlag" checked-children="有"
												  un-checked-children="无"/>
									</a-col>
									<a-col :span="8">二维码：
										<a-switch v-model:checked="qrcodeFlag" checked-children="有"
												  un-checked-children="无"/>
									</a-col>
									<a-col :span="8">条形码：
										<a-switch v-model:checked="barcodeFlag" checked-children="有"
												  un-checked-children="无"/>
									</a-col>
								</a-row>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="RFID：" name="rfidNum" v-if="rfidFlag"
										 :rules="[{ required: rfidFlag, message: '请输入RFID' }]">
								<a-input v-model:value.trim="formData.rfidNum" placeholder="请输入RFID" allow-clear/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="资产编号：" name="assetCode">
								<a-input v-model:value.trim="formData.assetCode" placeholder="请输入资产编号" allow-clear/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物品型号：" name="goodsModel">
								<a-input v-model:value.trim="formData.goodsModel" placeholder="请输入物品型号" allow-clear/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物品厂商：" name="goodsMfr">
								<a-input v-model:value.trim="formData.goodsMfr" placeholder="请输入物品厂商" allow-clear/>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="所属组织：" name="orgId">
								<a-tree-select
									v-model:value="formData.orgId"
									style="width: 100%"
									:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
									placeholder="请选择部门"
									allow-clear
									tree-default-expand-all
									:tree-data="orgTreeData"
									:tree-default-expanded-keys="orgTreeDefaultExpandedKeys"
									:field-names="{
										children: 'children',
										label: 'name',
										value: 'id'
									}"
								></a-tree-select>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="物品分类：" name="classId">
								<a-select
									v-model:value="formData.classId"
									:options="categoryOptions"
									placeholder="请选择分类"
									allow-clear
								></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="所属柜子：" name="cabInfo">
								<a-row>
									<a-col :span="8">
										<a-select
											v-model:value="formData.bioCabinetGroupId"
											:options="cabinetGroupOptions"
											placeholder="请选择柜组"
											allow-clear
											@change="onChangeCabGropu"
											style="width: 300px"
										></a-select>
									</a-col>
									<a-col :span="8">
										<a-select
											v-model:value="formData.bioCabinetId"
											:options="cabinetOptions"
											placeholder="请选择柜子"
											allow-clear
											@change="onChangeCabInfo"
											style="width: 300px"
										></a-select>
									</a-col>
									<a-col :span="8">
										<a-select
											v-model:value="formData.bioCabinetDoorId"
											:options="cabinetDoorOptions"
											placeholder="请选择柜门"
											allow-clear
											style="width: 300px"
										></a-select>
									</a-col>
								</a-row>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="物品管理员：" name="adminList">
								<a-button type="link" style="padding-left: 0px" @click="openSelector()">选择</a-button>
								<a-tag color="orange" v-for="item in selectedAdminUsers" :key="item.id">
									{{ item.name }}
								</a-tag>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="物品标签：" name="labels">
								<a-select
									v-model:value="formData.labels"
									:options="labelOptions"
									mode="multiple"
									placeholder="请选择标签"
									allow-clear
								></a-select>
							</a-form-item>
						</a-col>
					</a-row>
				</a-tab-pane>
				<a-tab-pane key="setting" tab="离柜设置">
					<a-collapse :activeKey="['1','2','3']">
						<a-collapse-panel key="1" header="离柜时间设置">
							<a-form-item label="最长离柜时限：" name="limitLeave">
								<a-space>
									<a-input-number v-model:value="formData.maxLimitLeave" placeholder="请输入最长离柜时限"
													:min="1" :max="100000" style="width: 300px"/>
									<a-select v-model:value="formData.maxLimitLeaveUnit" placeholder="请选择">
										<a-select-option value="1">分钟</a-select-option>
										<a-select-option value="2">小时</a-select-option>
										<a-select-option value="3">天</a-select-option>
									</a-select>
								</a-space>
							</a-form-item>
							<a-form-item label="到期前提示：" name="impend">
								<a-space>
									<a-input-number v-model:value="formData.impendPrompt" placeholder="请输入到期前提示"
													:min="1" :max="100000" style="width: 300px"/>
									<a-select v-model:value="formData.impendPromptUnit" placeholder="请选择">
										<a-select-option value="1">分钟</a-select-option>
										<a-select-option value="2">小时</a-select-option>
										<a-select-option value="3">天</a-select-option>
									</a-select>
								</a-space>
							</a-form-item>
							<a-form-item label="连续发送预警时间间隔：" name="alert">
								<a-space>
									<a-input-number v-model:value="formData.alertInterval" placeholder="请输入连续发送预警时间间隔"
													:min="1" :max="100000" style="width: 300px"/>
									<a-select v-model:value="formData.alertIntervalUnit" placeholder="请选择">
										<a-select-option value="1">分钟</a-select-option>
										<a-select-option value="2">小时</a-select-option>
										<a-select-option value="3">天</a-select-option>
									</a-select>
								</a-space>
							</a-form-item>
							<a-form-item label="连续发送预警最大次数：" name="alertMaxNum">
								<a-input-number v-model:value="formData.alertMaxNum" placeholder="请输入连续发送预警最大次数"
												:min="1" :max="100000" style="width: 300px"/>
							</a-form-item>
						</a-collapse-panel>
						<a-collapse-panel key="2" header="借还设置">
							<a-form-item label="支持扫码入库、借还：" name="ssbrFlag">
								<a-switch v-model:checked="ssbrFlag" checked-children="是"
										  :disabled="!qrcodeFlag&&!barcodeFlag"
										  un-checked-children="否"/>
							</a-form-item>
						</a-collapse-panel>
						<a-collapse-panel key="3" header="借还检查项设置">
							<a-button type="primary" @click="checkItemRef.onOpen()" style="margin-bottom: 16px">
								<template #icon>
									<plus-outlined/>
								</template>
								新增检查项
							</a-button>
							<a-table :columns="checkColumns" :data-source="formData.checkItems" bordered
									 :pagination="false">
								<template #bodyCell="{ column, record ,index }">
									<template v-if="column.dataIndex === 'applScene'">
										<a-space size="1">
											<a-tag v-if="record.borrowCheck === 1" color="green">借用检查</a-tag>
											<a-tag v-if="record.returnInsp === 1" color="orange">归还检查</a-tag>
										</a-space>
									</template>
									<template v-if="column.dataIndex === 'state'">
										<a-switch
											:checked="record.state === 1"
											checked-children="启用" un-checked-children="停用"
											@change="switchCheckItem(record,index)"
										/>
									</template>
									<template v-if="column.dataIndex === 'action'">
										<a-space size="2">
											<a-tooltip title="编辑">
												<a-button type="link" @click="editCheckItem(record,index)">
													<form-outlined/>
												</a-button>
											</a-tooltip>
											<a-tooltip title="移除">
												<a-button type="link" danger @click="removeCheckItem(index)">
													<delete-outlined/>
												</a-button>
											</a-tooltip>
										</a-space>
									</template>
								</template>
							</a-table>
						</a-collapse-panel>
					</a-collapse>
				</a-tab-pane>
				<a-tab-pane key="des" tab="描述信息">
					<a-form-item label="物品图片：" name="goodsImg">
						<a-upload
							v-model:file-list="formData.goodsImg"
							class="avatar-uploader"
							list-type="picture-card"
							:show-upload-list="false"
							:custom-request="customRequest"
							accept="image/png, image/jpeg, image/jpg"
						>
							<img v-if="imageUrl" :src="imageUrl" alt="avatar"
								 style="max-height: 100px; max-width: 100px"/>

							<div v-else>
								<plus-outlined/>
								<div class="ant-upload-text">上传</div>
							</div>
						</a-upload>
					</a-form-item>
					<a-form-item v-if="imageUrl">
						<a-button type="primary" danger @click="removeImg()">移除图片</a-button>
					</a-form-item>
					<a-form-item label="物品描述：" name="goodsDes">
						<xn-editor v-model="formData.goodsDes" placeholder="请输入物品描述" :height="200"></xn-editor>
					</a-form-item>
					<a-form-item label="注意事项：" name="attention">
						<xn-editor v-model="formData.attention" placeholder="请输入注意事项" :height="200"></xn-editor>
					</a-form-item>
					<a-form-item label="备注：" name="remarks">
						<a-textarea v-model:value="formData.remarks" placeholder="请输入备注" allow-clear :rows="4"/>
					</a-form-item>
				</a-tab-pane>
			</a-tabs>
		</a-form>

		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>

		<CheckItem ref="checkItemRef" @onBack="afterCheckItem"/>

		<admin-user-selector-plus
			ref="AdminUserSelectorPlus"
			page-url="/sys/role/userSelectorForRole"
			role-no="cabAdmin"
			@onBack="afterSelectUser"
		/>

	</a-drawer>
</template>

<script setup name="bizGoodsForm">
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import bizGoodsApi from '@/api/biz/bizGoodsApi'
	import bizUserApi from "@/api/biz/bizUserApi";
	import tool from "@/utils/tool";
	import bizCabinetGroupApi from "@/api/biz/bizCabinetGroupApi";
	import bizCabinetInfoApi from "@/api/biz/bizCabinetInfoApi";
	import bizCabinetDoorApi from "@/api/biz/bizCabinetDoorApi";
	import adminUserSelectorPlus from '@/components/Selector/adminUserSelectorPlus.vue'
	import CheckItem from './checkItem.vue'
	import XnEditor from '@/components/Editor/index.vue'
	import fileApi from '@/api/dev/fileApi'
	import sysConfig from '@/config'


	// 抽屉状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const checkItemRef = ref()
	// 表单数据
	const formData = ref({})
	const submitLoading = ref(false)
	const activeKey = ref('base')

	const rfidFlag = ref(false)
	const qrcodeFlag = ref(false)
	const barcodeFlag = ref(false)
	const ssbrFlag = ref(false)

	const orgTreeData = ref([])
	const orgTreeDefaultExpandedKeys = ref([])

	const AdminUserSelectorPlus = ref()
	//选择的超管人员
	const selectedAdminUsers = ref([])
	//物品分类
	const categoryOptions = ref([])
	//物品标签
	const labelOptions = ref([])
	//柜组
	const cabinetGroupOptions = ref([])
	//柜子
	const cabinetOptions = ref([])
	//柜门
	const cabinetDoorOptions = ref([])
	//图片
	const imageUrl = ref('')
	//检查项坐标
	const checkItemIndex = ref(-1);

	const checkColumns = [
		{
			title: '检查项',
			dataIndex: 'checkItem',
		},
		{
			title: '描述',
			dataIndex: 'checkDes',
		},
		{
			title: '适用场景',
			dataIndex: 'applScene',
			width: 200
		},
		{
			title: '状态',
			dataIndex: 'state',
			width: 100
		},
		{
			title: '操作',
			dataIndex: 'action',
			width: 100
		}
	]

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		loadCategory()
		loadLabel()
		loadOrgTree()
		loadCabGroup()
		formData.value.maxLimitLeaveUnit = "1"
		formData.value.impendPromptUnit = "1"
		formData.value.alertIntervalUnit = "1"
		if (record) {
			loadData(record)
		}
	}

	const loadData = (record) => {
		bizGoodsApi.bizGoodsDetail({
			goodsId: record.id
		}).then((data) => {
			rfidFlag.value = data.rfidFlag === 1
			qrcodeFlag.value = data.qrcodeFlag === 1
			barcodeFlag.value = data.barcodeFlag === 1
			ssbrFlag.value = data.ssbrFlag === 1
			if (data.bioCabinetGroupId) {
				onChangeCabGropu(data.bioCabinetGroupId)
			}
			if (data.bioCabinetId) {
				onChangeCabInfo(data.bioCabinetId)
			}
			let recordData = cloneDeep(data)
			if (record.goodsImg) {
				//组件是个数组
				recordData.goodsImg = [record.goodsImg]
				// 让其回显
				imageUrl.value = sysConfig.API_URL + '/dev/file/download?id=' + record.goodsImg
			} else {
				recordData.goodsImg = []
			}
			//处理标签
			let labels = []
			data.labels.map((item) => {
				labels.push(item)
			})
			recordData.labels = labels
			//处理几个单位
			if (data.maxLimitLeaveUnit) {
				recordData.maxLimitLeaveUnit = data.maxLimitLeaveUnit + ''
			} else {
				recordData.maxLimitLeaveUnit = "1"
			}
			if (data.impendPromptUnit) {
				recordData.impendPromptUnit = data.impendPromptUnit + ''
			} else {
				recordData.impendPromptUnit = "1"
			}
			if (data.alertIntervalUnit) {
				recordData.alertIntervalUnit = data.alertIntervalUnit + ''
			} else {
				recordData.alertIntervalUnit = "1"
			}
			//处理选择管理员
			let adminUser = []
			data.adminList.map((item) => {
				adminUser.push({
					id: item.id,
					name: item.name
				})
			})
			selectedAdminUsers.value = adminUser
			recordData.adminUserIds = data.adminList.map((item) => item.id).join(',')
			formData.value = Object.assign({}, recordData)
		})
	}


	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		visible.value = false
		rfidFlag.value = false
		qrcodeFlag.value = false
		barcodeFlag.value = false
		ssbrFlag.value = false
		selectedAdminUsers.value = []
		cabinetOptions.value = []
		cabinetDoorOptions.value = []
		activeKey.value = 'base'
		imageUrl.value = ''
		checkItemIndex.value = -1
	}
	// 默认要校验的
	const formRules = {
		goodsCode: [required('请输入编号')],
		goodsName: [required('请输入名称')],
	}
	// 打开人员选择器，选择主管
	const openSelector = () => {
		let userIds = selectedAdminUsers.value.map((user) => user.id)
		AdminUserSelectorPlus.value.showUserPlusModal(userIds)
	}
	// 人员选择器回调
	const afterSelectUser = (value) => {
		selectedAdminUsers.value = value
		formData.value.adminUserIds = value.map((item) => item.id).join(',')
	}
	//加载部门
	const loadOrgTree = () => {
		// 机构选择器数据
		bizUserApi.userOrgTreeSelector({
			orgType: 0
		}).then((res) => {
			if (res !== null) {
				orgTreeData.value = res
				// 默认展开2级
				orgTreeData.value.forEach((item) => {
					// 因为0的顶级
					if (item.parentId === '0') {
						orgTreeDefaultExpandedKeys.value.push(item.id)
						// 取到下级ID
						if (item.children) {
							item.children.forEach((items) => {
								orgTreeDefaultExpandedKeys.value.push(items.id)
							})
						}
					}
				})
			}
		})
	}
	//加载分类
	const loadCategory = () => {
		categoryOptions.value = tool
			.dictTypeList('GOODS_CATEGORY')
			.filter((item) => {
				// 排除
				if (item.dictValue !== 'CATALOG') {
					return item
				}
			})
			.map((item) => {
				return {
					value: item['dictValue'],
					label: item['name']
				}
			})
	}
	//加载标签
	const loadLabel = () => {
		labelOptions.value = tool
			.dictTypeList('GOODS_LABEL')
			.filter((item) => {
				// 排除
				if (item.dictValue !== 'CATALOG') {
					return item
				}
			})
			.map((item) => {
				return {
					value: item['dictValue'],
					label: item['name']
				}
			})
	}
	//加载柜组
	const loadCabGroup = () => {
		bizCabinetGroupApi.bizCabinetGroupList({}).then((res) => {
			cabinetGroupOptions.value = res.map((item) => {
				return {
					label: `${item.cabinetGroupCode}-${item.cabinetGroupName}`,
					value: item.id
				}
			})
		})
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				if (formDataParam.goodsImg) {
					formDataParam.goodsImg = formDataParam.goodsImg[0]
				}
				formDataParam.rfidFlag = rfidFlag.value ? 1 : 0
				formDataParam.qrcodeFlag = qrcodeFlag.value ? 1 : 0
				formDataParam.barcodeFlag = barcodeFlag.value ? 1 : 0
				formDataParam.ssbrFlag = ssbrFlag.value ? 1 : 0;
				formDataParam.goodsType = 0
				bizGoodsApi
					.bizGoodsSubmitForm(formDataParam, !formDataParam.id)
					.then(() => {
						onClose()
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
	}
	//柜组切换
	const onChangeCabGropu = (value) => {
		formData.value.bioCabinetId = undefined
		formData.value.bioCabinetDoorId = undefined
		cabinetOptions.value = []
		cabinetDoorOptions.value = []
		bizCabinetInfoApi.bizCabinetList({ groupId: value }).then((res) => {
			cabinetOptions.value = res.map((item) => {
				return {
					label: `${item.cabinetName}`,
					value: item.id
				}
			})
		})

	}
	//柜子切换
	const onChangeCabInfo = (value) => {
		formData.value.bioCabinetDoorId = undefined
		cabinetDoorOptions.value = []
		bizCabinetDoorApi.bizCabinetDoorList({ cabinetInfoId: value }).then((res) => {
			cabinetDoorOptions.value = res.map((item) => {
				return {
					label: `${item.cabinetDoorName}`,
					value: item.id
				}
			})
		})

	}
	const customRequest = (data) => {
		formData.value.goodsImg = ref([])
		const fileData = new FormData()
		fileData.append('file', data.file)
		fileApi
			.fileUploadReturnId(fileData)
			.then((res) => {
				imageUrl.value = sysConfig.API_URL + '/dev/file/download?id=' + res
				formData.value.goodsImg.push(res)
				data.onSuccess()
			})
		// getBase64(data.file)
		// 	.then((res) => {
		// 		imageUrl.value = res
		// 		formData.value.goodsImg.push(res)
		// 	})
		// 	.catch((err) => {
		// 	})

	}
	// 文件转base64，用于显示图片
	const getBase64 = (file) => {
		return new Promise((resolve, reject) => {
			// FileReader类就是专门用来读文件的
			const reader = new FileReader()
			reader.readAsDataURL(file)
			// 成功和失败返回对应的信息，reader.result一个base64，可以直接使用
			reader.onload = () => resolve(reader.result)
			// 失败返回失败的信息
			reader.onerror = (error) => reject(error)
		})
	}
	// 检查项选择器回调
	const afterCheckItem = (data) => {
		console.warn("aaa=>", checkItemIndex.value)
		console.warn("bbbb=>", checkItemIndex.value ? 1 : 0)
		if (checkItemIndex.value >= 0) {
			formData.value.checkItems.splice(checkItemIndex.value, 1, data)
		} else {
			let checkItems = [];
			if (formData.value.checkItems) {
				formData.value.checkItems.map((item) => {
					checkItems.push(item);
				})
			}
			checkItems.push(data)
			formData.value.checkItems = checkItems
		}
		checkItemIndex.value = -1
	}
	// 移除检查项
	const removeCheckItem = (index) => {
		formData.value.checkItems.splice(index, 1)
	}
	// 切换检查项
	const switchCheckItem = (record, index) => {
		formData.value.checkItems[index].state = record.state === 1 ? 0 : 1
	}
	//编辑检查项
	const editCheckItem = (record, index) => {
		checkItemIndex.value = index;
		checkItemRef.value.onOpen(record)
	}
	//移除图片
	const removeImg = () => {
		formData.value.goodsImg = ref([])
		imageUrl.value = ''
	}

	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
